package cn.schoolwow.workflow.module.task.action.flow.complete.transaction;

import cn.schoolwow.quickdao.domain.database.dql.condition.Condition;
import cn.schoolwow.quickdao.domain.transaction.Transaction;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.domain.instance.WorkFlowInstanceStatus;
import cn.schoolwow.workflow.domain.task.CompleteTaskRequest;
import cn.schoolwow.workflow.domain.task.TaskType;
import cn.schoolwow.workflow.entity.WorkFlowInstance;
import cn.schoolwow.workflow.entity.WorkFlowNode;
import cn.schoolwow.workflow.module.task.action.domain.CompleteTaskOption;

public class UpdateWorkFlowInstanceAndTaskFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        CompleteTaskRequest completeTaskRequest = flowContext.getInstanceData(CompleteTaskRequest.class);
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        WorkFlowNode nextNode = flowContext.checkData("nextNode", WorkFlowNode.class);
        CompleteTaskOption completeTaskOption = flowContext.checkInstanceData(CompleteTaskOption.class);
        Transaction transaction = flowContext.checkInstanceData(Transaction.class);

        transaction.addRecordString("根据工作流实例当前节点,状态,上下文数据和元数据");
        Condition condition = transaction.query(WorkFlowInstance.class)
                .addQuery("id", workFlowInstance.getId())
                .addQuery("definitionId", workFlowInstance.getDefinitionId())
                .addUpdate("contextData", workFlowInstance.getContextData())
                .addUpdate("meta", workFlowInstance.getMeta());
        if(completeTaskOption.shouldUpdateInstanceCurrentNodeId){
            condition.addUpdate("workFlowNodeId", nextNode.getId());
        }
        if(null!=completeTaskRequest&&TaskType.REJECT.equals(completeTaskRequest.taskType)){
            condition.addUpdate("status", WorkFlowInstanceStatus.Reject.status);
        }else if(nextNode.getType()==2){
            condition.addUpdate("status", WorkFlowInstanceStatus.Finished.status);
        }else if(completeTaskOption.instanceFinished){
            condition.addUpdate("status", WorkFlowInstanceStatus.Finished.status);
        }
        condition.execute().update();
    }

    @Override
    public String name() {
        return "完成流程任务-更新工作流实例和任务";
    }

}
